﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GradeBook.Models;

namespace GradeBook.Daos
{
    public class TaskDao
    {
        public static List<Task> Load()
        {
            using (GradeBookEntities db = new GradeBookEntities())
                return db.Task.ToList();
        }

        public static List<Task> LoadByUserId(int userId)
        {
            using (GradeBookEntities db = new GradeBookEntities())
                return (
                    from rtu in db.RelTaskUser
                    from t in db.Task
                    where rtu.TaskId == t.Id
                    where rtu.UserId == userId
                    select t).ToList();
        }

        public static Task GetById(int id)
        {
            using (GradeBookEntities db = new GradeBookEntities())
                return db.Task.FirstOrDefault(g => g.Id == id);
        }

        public static void Add(Task task)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.Task.AddObject(task);
                db.SaveChanges();
            }
        }
        public static void Update(Task task)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.Task.ApplyCurrentValues(task);
                db.SaveChanges();
            }
        }
        public static void Remove(int id)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.Task.DeleteObject(db.Task.FirstOrDefault(g => g.Id == id));
                db.SaveChanges();
            }
        }
    }
}